package com.bw.home

import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.home.databinding.ActivityLoginBinding
import com.bw.home.intent.LoginIntent
import com.bw.home.state.LoginState
import com.bw.home.viewmodel.LoginViewModel
import com.bw.lib_common.ConstValue
import com.bw.lib_mvi.BaseActivity
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = ConstValue.LOGIN)
class LoginActivity : BaseActivity() {
    lateinit var binding: ActivityLoginBinding
    lateinit var viewModel: LoginViewModel


    override fun getRootLayout(): View {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
        super.initView()
        viewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
    }

    override fun initData() {
        super.initData()
        //登录
        binding.loginBt.setOnClickListener {
            goLogin()
        }

        //前往注册
        binding.loginGoRegister.setOnClickListener {
            ARouter.getInstance().build(ConstValue.REGISTER).navigation()
        }
    }

    private fun goLogin() {
        lifecycleScope.launch {
            viewModel.intents.send(
                LoginIntent.login(
                    binding.loginUsernameEt.text.toString(),
                    binding.loginPasswordEt.text.toString()
                )
            )
        }
    }

    override fun initEvent() {
        super.initEvent()
        lifecycleScope.launch {
            viewModel.state.collect {
                when (it) {

                    is LoginState.login -> {
                        ToastUtils.showLong("登陆成功")
                        SPUtils.getInstance().put("token", it.data.token)
                        SPUtils.getInstance().put("login", true)
                        finish()
                    }

                    is LoginState.Failed -> {
                        Log.d("TagA", "登录失败: $it")
                    }

                    else -> {}
                }
            }
        }
    }
}